package com.nicefact.mailmonitor.dao;

/**
*
*/

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;


import com.nicefact.mailmonitor.connections.PMF;
import com.nicefact.mailmonitor.entity.AppUser;



/**
* Abstract DAO class containing common DAO subset implementation.
* 
*/
public abstract class AbstractDao<E>  {
	
	protected final Logger log = Logger.getLogger(getClass().getName());

	public PersistenceManager getPersistenceManager(){
		return PMF.get().getPersistenceManager();
	}

	/**
	 * Create an object in the persistence storage.
	 * 
	 * @param object
	 *            to persist.
	 * @return persisted object.
	 */
	
	
	public E create(E object) {
		PersistenceManager pm = getPersistenceManager();
		try{
			object = pm.makePersistent(object);
		}finally{
			pm.close();
		}
		return object;

	}
	
	/**
	 * Create objects at once in the persistence storage.
	 * 
	 * @param entities
	 *            the collection objects to persist.
	 * @return collection of persisted objects.
	 */
	public Collection<E> createAll(Collection<E> entities) {
		log.log(Level.INFO,"Create method started for all entities in collection.");
	/*	for(Object obj : entities)
			setSystemProperties(obj, (Class<E>)obj.getClass());*/
		return getPersistenceManager().makePersistentAll(entities);
	}

	/**
	 * Remove an object from the persistence storage, Big Table in this case.
	 * 
	 * @param object to remove.
	 */
	public boolean remove(Object object){
		boolean success = false;
		PersistenceManager pm = getPersistenceManager();
		try{
			pm.deletePersistent(object);
			success = true;
		}finally{
			pm.close();
		}		
		return success;
	}
	
	public boolean removeAll(Collection<E> object){
		boolean success = false;
		PersistenceManager pm = getPersistenceManager();
		try{
			pm.deletePersistentAll(object);
			success = true;
		}finally{
			pm.close();
		}		
		return success;
	}
	
	protected List<E> getAllObjects(Class<E> type){
		PersistenceManager pm = getPersistenceManager();
		Query query =  pm.newQuery(type);
		List<E> objectList = new ArrayList<E>();
		try{
			List<E> results = (List<E>)query.execute();
			if(!results.isEmpty()){
				for(E template : results){
					E detached = pm.detachCopy(template);
					objectList.add(detached);
				}
			}
		}finally{
			query.closeAll();
			pm.close();
		}
		return objectList;
	}
	
	 public E get(Class<E> type, Object key){
			PersistenceManager pm = getPersistenceManager();
			Object object = null;
			try{
				object =  pm.detachCopy(pm.getObjectById(type,key));
			}finally{
				pm.close();
			}
			return (E)object;
		}

}